package com.biaobiaoqi.scoreanalysis.action;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;

import com.biaobiaoqi.scoreanalysis.exception.AuthenticateFailedException;
import com.biaobiaoqi.scoreanalysis.hibernate.bean.Administrator;
import com.biaobiaoqi.scoreanalysis.service.IAdministratorService;
import com.opensymphony.xwork2.ActionSupport;

public class TreateLogin extends ActionSupport implements SessionAware {
	private static final Log log = LogFactory.getLog(TreateLogin.class);
	private static final long serialVersionUID = -8871720762183492716L;

	private String userName;
	private String password;
	private String role;
	private String validateCode;
	private Map<String, Object> session;

	@Resource
	IAdministratorService administratorService;

	public String execute() {
		log.debug("Login: userName[" + userName + "] " + "password["
				+ password + "] " + "role[" + role + "] "
				+ "validateCode[" + validateCode + "] "
				+ "expected validateCode["
				+ session.get("validateCode") + "]");
 		try {
			if ("administrator".equals(role)
					&& session.get("validateCode").equals(validateCode)) {
				Administrator administrator = administratorService
						.authenticateAdministrator(userName, password);
				session.put("userType", "administrator");
				session.put("userId", administrator.getId());
				session.put("userName", administrator.getName());
				return "administrator";
			} else if ("student".equals(role)) {
				return "student";
			} else if ("teacher".equals(role)) {
				return "teacher";
			} else {
				addActionError("非法参数");
				return INPUT;
			}
		} catch (AuthenticateFailedException e) {
			addActionError("用户名或密码错误！");
			return INPUT;
		} catch (Exception e) {
			addActionError("服务器内部错误！");
			e.printStackTrace();
			return INPUT;
		}
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public IAdministratorService getAdministratorService() {
		return administratorService;
	}

	public void setAdministratorService(
			IAdministratorService administratorService) {
		this.administratorService = administratorService;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;

	}
}
